<template>
  <div>
    <van-nav-bar title="用户注册" :fixed="true"/>
    <div style="margin-top: 40px">
      <van-form @submit="onSubmit">
        <van-field
            v-model="username"
            name="username"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
            v-model="password"
            type="password"
            name="password"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
            v-model="confirmPassword"
            type="password"
            name="validator"
            label="确认密码"
            placeholder="确认密码"
            :rules="[{ validator, message: '输入的两次密码不一致' }]"
        />
        <div style="margin: 16px;">
          <van-button round block type="warning" native-type="submit">注册</van-button>
        </div>
      </van-form>
    </div>
    <div class="signupTips">
      <router-link to="/login">已有账号去登录</router-link>
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {
  name: "Signup",
  data() {
    return {
      username: '',
      password: '',
      confirmPassword: ''
    }
  },
  methods: {
    validator(val) {
      if (val === this.password){
        return true
      }
      return false
    },
    onSubmit() {
      const user = {
        username: this.username,
        password: this.password
      }
      this.request.post("/api/user/register", user).then(res => {
        if (res.code === 1) {
          localStorage.setItem("user", JSON.stringify(res.data))
          this.$store.commit('SIGNUPINFO',user)
          //跳转页面
          this.$router.push("/login")
          this.$notify({
            type: 'success',
            message: '注册成功，可以登录了',
            duration: 1000
          })
        }
      })
    },
  }

}
</script>

<style lang="less" scoped>
.signupTips {
  a:hover {
    color: red;
  }

  a {
    color: #1989fa;
    margin-right: 20px;
  }

  display: flex;
  justify-content: right;
}
</style>